package util;

import com.google.api.translate.Language;
import com.google.api.translate.Translate;

/**
 * The Translator {@code class} containing all necessary method for translate
 * word.
 * 
 * @author Peter NGO, Guillaume POUSSEL and Mathieu RUL
 * 
 * @version 1.0
 */
public class Translator {

	/**
	 * Referrer used by Google search.
	 */
	private static final String REFERRER = "http://www.google.fr/";

	/**
	 * Translate a string from English to French.
	 * 
	 * @param string
	 *            The English string.
	 * 
	 * @return the translated string.
	 * 
	 * @throws Exception
	 *             If translate are unavailable, for example if Interned is
	 *             turned off.
	 */
	private static String englishToFrench(String string) throws Exception {
		Translate.setHttpReferrer(REFERRER);
		return Translate.execute(string, Language.ENGLISH, Language.FRENCH);
	}

	/**
	 * Verify if two string are equivalent.
	 * 
	 * @param string1
	 *            The first string to test.
	 * 
	 * @param string2
	 *            The second string to test.
	 * 
	 * @return {@code true} if the strings are equivalent; {@code false}
	 *         otherwise.
	 * 
	 * @throws Exception
	 *             If translate are unavailable, for example if Interned is
	 *             turned off.
	 */
	public static boolean equivalent(String string1, String string2)
			throws Exception {
		string1 = string1.toLowerCase();
		string2 = string2.toLowerCase();
		String[] strings1 = new String[] { string1, englishToFrench(string1),
				frenchToEnglish(string1) };
		String[] strings2 = new String[] { string2, englishToFrench(string2),
				frenchToEnglish(string2) };
		for (String trad2 : strings2) {
			for (String trad1 : strings1) {
				if (trad2.equals(trad1))
					return true;
			}
		}
		return false;
	}

	/**
	 * Translate a string from French to English.
	 * 
	 * @param string
	 *            The French string.
	 * 
	 * @return the translated string.
	 * 
	 * @throws Exception
	 *             If translate are unavailable, for example if Interned is
	 *             turned off.
	 */
	private static String frenchToEnglish(String string) throws Exception {
		Translate.setHttpReferrer(REFERRER);
		return Translate.execute(string, Language.FRENCH, Language.ENGLISH);
	}
}
